//
//  WaitTake.m
//  RRQS
//
//  Created by kyjun on 16/3/23.
//
#import "WaitTake.h"
#import "TaskHeader.h"
#import "WaitTaskCell.h"
#import "TaskFooter.h"
#import "MOrder.h"
//#import "WaitTakeDetail.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "WJWaiMaiDodel.h"
#import "WaitTakeDetailViewController.h"
#import "PaotuiDetailViewController.h"
#define wmCount self.listDataMarray.count

@interface WaitTake ()<DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property(nonatomic,strong) NSMutableArray* arrayData;
@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;
@property(nonatomic,strong) NSString* footerIdentifier;
@property (nonatomic, strong) WJWaiMaiDodel *waiMaiDodel; //数据源.item
@property (nonatomic, strong) NSMutableArray *listDataMarray; // 外卖数据源
@property (nonatomic, strong) NSMutableArray *hlistDataMarray; // 跑腿数据源
@property (nonatomic, assign) NSInteger totalCountInteger; // 总数
@end

@implementation WaitTake


-(instancetype)init{
    self = [super initWithCollectionViewLayout:[[UICollectionViewFlowLayout alloc]init]];
    if(self){
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.cellIdentifier = @"WaitTaskCell";
    self.headerIdentifier = @"WaitTaskHeader";
    self.footerIdentifier = @"WaitTaskFooter";
    [self layoutUI];
    [self layoutConstraints];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData:) name:NotificationRemotePm object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData:) name:NotificationGrabOrderRefreshWaitOrder object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData:) name:NotificationRefreshWaitTask object:nil];
    
    // 启动倒计时管理
    [kCountDownManager start];

}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(self.Identity.userInfo.isLogin){
        [self refereshDatasource];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark =====================================================  user interface layout
-(void)layoutUI{
    [self.collectionView registerClass:[WaitTaskCell class] forCellWithReuseIdentifier:NSStringFromClass([WaitTaskCell class])];
    
    [self.collectionView registerClass:[TaskHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:self.headerIdentifier];
    [self.collectionView registerClass:[TaskFooter class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:self.footerIdentifier];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.collectionView.emptyDataSetSource = self;
    self.collectionView.emptyDataSetDelegate = self;
}

-(void)layoutConstraints{
    self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.f]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.f]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.f]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.f]];

}

#pragma mark =====================================================  Datasource
-(void)queryData{
    NSDictionary* arg = @{@"ince":@"get_rr_help_wait_order_list",@"emp_id":self.Identity.userInfo.userID};
    [DBNet PostURL:kHost parameters:arg succeed:^(NSDictionary *data) {
        [WMHelper outPutJsonString:data];
        NSInteger flag = [[data objectForKey:@"status"]integerValue];
        if(flag == 1){
#warning  TODO:当有订单从后台修改了状态 用户在刷新的时候需要刷新   这里可以作为一个通知最佳
//            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationHomeRefreshing object:nil];
            [self.arrayData removeAllObjects];
            [self.listDataMarray removeAllObjects];
            [self.hlistDataMarray removeAllObjects];
            
            self.waiMaiDodel = [WJWaiMaiDodel yy_modelWithDictionary:data];
            [self.listDataMarray addObjectsFromArray:self.waiMaiDodel.list];
            [self.hlistDataMarray addObjectsFromArray:self.waiMaiDodel.hlist];
            //获取数量
            if (self.WaitTakeNumBlock) {
                self.WaitTakeNumBlock([NSString stringWithFormat:@"%@", data[@"total_num"]]);
            }
           

            if ([WMHelper isNULLOrnil:self.listDataMarray]) {
                if ([WMHelper isNULLOrnil:self.hlistDataMarray]) {
                    self.totalCountInteger = 0;
                }else{
                    self.totalCountInteger = self.hlistDataMarray.count;
                }
            }
            if ([WMHelper isNULLOrnil:self.hlistDataMarray]) {
                if ([WMHelper isNULLOrnil:self.listDataMarray]) {
                    self.totalCountInteger = 0;
                }else{
                    self.totalCountInteger = self.listDataMarray.count;
                }
            }
            if (![WMHelper isNULLOrnil:self.listDataMarray] && ![WMHelper isNULLOrnil:self.hlistDataMarray]) {
                self.totalCountInteger = self.listDataMarray.count + self.hlistDataMarray.count;
            }
            [self.collectionView reloadData];
        }else{
            [self alertHUD:[data objectForKey:@"fail"]];
        }
        [self.collectionView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        NSLog(@"%@",error.debugDescription);
        [self alertHUD:@"网络异常"];
        [self.collectionView.mj_header endRefreshing];
    }];    
}

-(void)refereshDatasource{
    __weak typeof(self) weakSelf = self;
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf queryData];
    }];
    [self.collectionView.mj_header beginRefreshing];
}

#pragma mark =====================================================  <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    WaitTaskCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([WaitTaskCell class]) forIndexPath:indexPath];
    
    if (![WMHelper isNULLOrnil:self.listDataMarray]) { // 如果数组不为空(外卖)
        if (indexPath.section < self.listDataMarray.count) {
            cell.waiMaiDodelListitems = ((WJWaiMaiDodelList *)self.listDataMarray[indexPath.section]).items[0];
        }else{
            cell.waiMaiDodelHList = self.hlistDataMarray[indexPath.section - wmCount];
        }
    }else{// 跑腿 self.listDataMarray数组为空的时候
        cell.waiMaiDodelHList = self.hlistDataMarray[indexPath.section];
    }
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.totalCountInteger;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if([kind isEqualToString:UICollectionElementKindSectionHeader]){
        UICollectionReusableView  *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:self.headerIdentifier forIndexPath:indexPath];
        TaskHeader *header = (TaskHeader *) reusableView;
        if (indexPath.section < self.listDataMarray.count) {
            header.waiMaiDodelList = self.listDataMarray[indexPath.section];
        }else{
            header.waiMaiDodelHList = self.hlistDataMarray[indexPath.section - wmCount];
        }
        return reusableView;
    }else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
        
        // 增加倒计时源
        [kCountDownManager addSourceWithIdentifier:[NSString stringWithFormat:@"OYPagingSource%zd", indexPath.section]];
        
        UICollectionReusableView  *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:self.footerIdentifier forIndexPath:indexPath];
        TaskFooter *footer = (TaskFooter *) reusableView;
        footer.isWaitTake = YES;
        if (indexPath.section < self.listDataMarray.count) {
            footer.waiMaiDodelList = self.listDataMarray[indexPath.section];
          
            footer.countDownListZero = ^(WJWaiMaiDodelList *waiMaiDodelListModel) {
                // 回调
                if (!waiMaiDodelListModel.timeOut) {
                    [self.collectionView reloadData];
                    NSLog(@"--时间到了");
                }
                // 标志
                waiMaiDodelListModel.timeOut = YES;
            };
        }else{
            footer.waiMaiDodelHList = self.hlistDataMarray[indexPath.section - wmCount];
            footer.countDownZero = ^(WJWaiMaiDodelHList *waiMaiDodelHListModel) {
                // 回调
                if (!waiMaiDodelHListModel.timeOut) {
                    [self.collectionView reloadData];
                    NSLog(@"--时间到了");
                }
                // 标志
                waiMaiDodelHListModel.timeOut = YES;
            };
        }
        

        footer.routeBlock = ^(BOOL isPaoTui, WJWaiMaiDodelHList *hListModel, WJWaiMaiDodelList *listModel) {
            if (isPaoTui) {
                [CommonUntils naviAddressWithDestination:hListModel.get_address withLatitude:hListModel.lat withLongitude:hListModel.lng withController:self];
                
                
            }else{
                WJWaiMaiDodelListitems *item = listModel.items[0];
                [CommonUntils naviAddressWithDestination:item.site_addr withLatitude:listModel.lat withLongitude:listModel.lng withController:self];
                
            }
            
        };

        footer.reachBlock = ^(BOOL isPaoTui, NSString *title,WJWaiMaiDodelHList *waiMaiDodelHListModel, WJWaiMaiDodelList *waiMaiDodelListModel) {
            

            NSString *main_id;
            if (isPaoTui) {
                main_id = waiMaiDodelHListModel.order_id;
            }else{
                WJWaiMaiDodelListitems *item = waiMaiDodelListModel.items[0];
                main_id = item.order_id;
            }
            NSDictionary* arg = @{@"ince":@"get_rr_help_wait_order_anniu",
                                  @"lat":self.Identity.locationInfo.lat,
                                  @"lng":self.Identity.locationInfo.lng,
                                  @"emp_id":self.Identity.userInfo.userID,
                                  @"main_id":main_id,
                                  @"types":isPaoTui ? @"2" :@"1",
                                  @"status":[title isEqualToString:@"上报到店"] ? @"1":@"2"//1.上报到店按钮 2.确认取货按钮
                                  };
            
            NSLog(@"上报到店还是确认取货%@",arg);
            [self showHUD];
            [DBNet PostURL:kHost parameters:arg succeed:^(NSDictionary *data) {
                [WMHelper outPutJsonString:data];
                NSInteger flag = [[data objectForKey:@"status"]integerValue];
                if(flag == 1){
                    [self hidHUD:@"成功" success:YES];
                    [[NSNotificationCenter defaultCenter]postNotificationName:NotificationRefreshShippedTask object:nil];

                }else{
                    [self hidHUD:[data objectForKey:@"sucess"]];
                }
                [self.collectionView.mj_header beginRefreshing];
            } failure:^(NSError *error) {
                NSLog(@"%@",error.description);
                [self hidHUD:@"网络异常"];
            }];
        };
        
       return reusableView;
    }
    return nil;
}
#pragma mark =====================================================  <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    WaitTakeDetailViewController *controller = [[WaitTakeDetailViewController alloc]init];
//    [self.navigationController pushViewController:controller animated:YES];
    
//    WaitTakeDetail* controller = [[WaitTakeDetail alloc]init];
//    controller.isWaitTask = YES;
//    controller.entity = self.arrayData[indexPath.section];
    
    if (![WMHelper isNULLOrnil:self.listDataMarray]) { // 如果数组不为空
        if (indexPath.section < self.listDataMarray.count) {
            WaitTakeDetailViewController *controller = [[WaitTakeDetailViewController alloc]init];
            controller.waiMaiDodelListitems = ((WJWaiMaiDodelList *)self.listDataMarray[indexPath.section]).items[0];
            [self.navigationController pushViewController:controller animated:YES];
        }else{
            PaotuiDetailViewController *controller = [[PaotuiDetailViewController alloc]init];
            controller.waiMaiDodelHList = self.hlistDataMarray[indexPath.section - wmCount];
            [self.navigationController pushViewController:controller animated:YES];
        }
    }else{// 跑腿 self.listDataMarray数组为空的时候
        PaotuiDetailViewController *controller = [[PaotuiDetailViewController alloc]init];
        controller.waiMaiDodelHList = self.hlistDataMarray[indexPath.section];
        [self.navigationController pushViewController:controller animated:YES];
    }
    
    
}
#pragma mark =====================================================  <UICollectionViewDelegateFlowLayout>
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(SCREEN_WIDTH, 60);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(SCREEN_WIDTH, 75);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
//    MOrder* empty = self.arrayData[section];
//    MSubOrder* item = (MSubOrder*)[empty.arraySubOrder firstObject];
//    if([WMHelper isEmptyOrNULLOrnil:item.phoneAddress]){
//        return CGSizeMake(SCREEN_WIDTH, 60);
//    }
    return CGSizeMake(SCREEN_WIDTH, 210);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0.f; /// 行与行之间的间隔距离
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0.f; //相邻两个 item 间距
}

#pragma mark =====================================================  DZEmptyData 协议实现
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc] initWithString:@"暂无待取货订单" attributes:@{NSFontAttributeName :[UIFont boldSystemFontOfSize:17.0],NSForegroundColorAttributeName:[UIColor grayColor]}];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return roundf(self.collectionView.frame.size.height/10.0);
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

#pragma mark =====================================================  Notification
-(void)refreshData:(NSNotification*)notification{
        [self.collectionView.mj_header beginRefreshing];
}

#pragma mark =====================================================  property package
-(NSMutableArray *)arrayData{
    if(!_arrayData){
        _arrayData = [[NSMutableArray alloc]init];
    }
    return _arrayData;
}

- (NSMutableArray *)listDataMarray
{
    if (!_listDataMarray) {
        _listDataMarray = @[].mutableCopy;
    }
    return _listDataMarray;
}
- (NSMutableArray *)hlistDataMarray
{
    if (!_hlistDataMarray) {
        _hlistDataMarray = @[].mutableCopy;
    }
    return _hlistDataMarray;
}
@end
